package com.hqyj.springBoot.modules.test.service.impl;

import com.hqyj.springBoot.modules.common.vo.Result;
import com.hqyj.springBoot.modules.common.vo.Search;
import com.hqyj.springBoot.modules.test.dao.StudentDao;
import com.hqyj.springBoot.modules.test.entity.Student;
import com.hqyj.springBoot.modules.test.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    @Transactional
    public Result<Student> insertStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Insert success",
                student);
    }

    @Override
    @Transactional
    public Result<Student> updateStudent(Student student) {
//        studentDao.saveAndFlush(student);
        studentDao.updateStudent(student);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Update success",
                student);
    }

    @Override
    @Transactional
    public Result<Object> deleteStudentById(int id) {
        studentDao.deleteById(id);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Delete success");
    }

    @Override
    public Student getStudentById(int id) {
//        return studentDao.getById(id);
        return studentDao.getStudentById(id);
    }

    @Override
    public Page<Student> getStudentBySearch(Search search) {
        search.init();

        //构造pageable对象
        Sort.Direction direction = StringUtils.isBlank(search.getDirection()) ||
                search.getDirection().toLowerCase().equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC;
        String order = StringUtils.isBlank(search.getSort()) ? "id" :search.getSort();
        Sort sort = Sort.by(direction,order);

        Pageable pageable = PageRequest.of(
                search.getCurrentPage() - 1,
                search.getPageSize(),
                sort
                );

        //构造Example对象

        //创建查询模板
        Student student = new Student();
        student.setName(search.getKeyword());
        //构造匹配规则
        ExampleMatcher matcher = ExampleMatcher.matchingAny()//连接条件是or用any,连接条件是and用all
                .withMatcher("name",match -> match.contains())
                .withIgnorePaths("age");//忽略一些字段,忽略基本数据类型,基本数据类型默认值为0,不忽略以0位查询条件
        Example<Student> example = Example.of(student,matcher);

        return studentDao.findAll(example , pageable);
    }

    @Override
    public Student findFirstByName(String name) {
        return studentDao.findFirstByName(name);
    }
}
